<?php

/**
 * 用户接口
 */
class UserController extends ControllerBase {

    /**
     * 更新用户信息 [POST]
     * 接口请求地址：/user/modify/
     * @param int $uid 用户Id 如果uid=0,则为创建用户，uid>0则为修改资料
     * @param string $name 昵称
     * @param string $phone 手机号码
     * @param string $passwd 密码明文
     * @param int $sex 性别(0男1女)
     * @example 新增用户必须传[密码]和[电话号码]
     * @example 返回结果：{"retcode":0,"retmsg":uid}，如果是修改：{"retcode":0,"retmsg":"Success"}
     * @example 注册成功之后，retmsg的值即为uid，请做本地存储
     */
    public function modifyAction() {
        $uid = intval($this->request->getPost('uid'));
        $name = trim($this->request->getPost('name'));
        $phone = trim($this->request->getPost('phone'));
        $passwd = trim($this->request->getPost('passwd'));
        $sex = $this->request->get('sex');
        $sex = $sex == 0 ? 'm' : 'f';
        if ($uid > 0) {
            // 编辑资料
            $user = User::FindFirst("client_id = $uid");
            if ($user === false) {
                // 用户不存在
                $this->echoErrcode(ErrorCode::$ERR_USER_DOESNOTEXT);
                return;
            }
        } else {
            // 新增用户必须传密码，电话号码
            if ($uid == 0) {
                if (empty($passwd) || empty($phone)) {
                    $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
                    return;
                }
                // 检查电话
                $extCheck = User::FindFirst("client_phone = $phone");
                if ($extCheck !== false) {
                    // 电话号码已存在
                    $this->echoErrcode(ErrorCode::$ERR_USER_PHONEEXT);
                    return;
                } else {
                    if (!preg_match("/^1[3|4|5|7|8][0-9]\\d{8}$/", $phone)) {
                        return $this->echoErrcode(ErrorCode::$ERR_USERREG_PHONEERR);
                    }
                    // 新增用户
                    $user = new User();
                    $user->client_joindate = date('Y-m-d');
                    $user->client_phone = $phone;
                    // 注册默认积分
                    $credit_newuser = intval(Settings::get('credit_newuser'));
                    if ($credit_newuser > 0) {
                        $user->client_credit = $credit_newuser;
                    }
                }
            }
        }
        !empty($passwd) && $user->client_password = sha1($passwd);
        !empty($sex) && $user->client_sex = $sex;
        !empty($name) && $user->client_nickname = $name && $user->client_name = $name;
        try {
            $user->save();
            if ($uid > 0) {
                $this->echoSuccess();
            } else {
                $this->echoMsg(0, intval($user->client_id));
            }
        } catch (Exception $ex) {
            $this->echoErrcode(ErrorCode::$ERR_USERMODIFY_FAILED);
        }
    }

    /**
     * 用户鉴权 [POST]
     * 接口请求地址：/user/identify/
     * @param string $phone 电话号码
     * @param string $passwd 明文密码
     * @example 返回结果：{"retcode":0,"retmsg":{uid:用户Id}}
     */
    public function identifyAction() {
        $phone = $this->request->getPost('phone');
        $passwd = $this->request->getPost('passwd');
        if (!empty($phone) && !empty($passwd)) {
            $passwd = sha1($passwd);
            $user = User::FindFirst("client_phone = '$phone' AND client_password = '$passwd'");
            if (false !== $user) {
                $this->echoMsg(0, array("uid" => intval($user->client_id)));
            } else {
                $this->echoErrcode(ErrorCode::$ERR_USERVALIDATE_FAILED);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 修改密码 [POST]
     * 接口请求地址：/user/change_passwd/
     * @param int $phone 手机号码
     * @param string $passwd 新密码
     * @example 返回结果：{"retcode":0,"retmsg":{uid:用户Id}}
     */
    public function change_passwdAction() {
        $phone = $this->request->getPost('phone');
        $passwd = $this->request->getPost('passwd');
        if (!empty($phone) && !empty($passwd)) {
            $passwd = sha1($passwd);
            $user = User::FindFirst("client_phone = '$phone'");
            if (false !== $user) {
                $user->client_password = $passwd;
                try {
                    $user->save();
                    $this->echoMsg(0, array("uid" => intval($user->client_id)));
                } catch (Exception $ex) {
                    $this->echoErrcode(ErrorCode::$ERR_SYSTEM_FAILED);
                }
            } else {
                $this->echoErrcode(ErrorCode::$ERR_USERVALIDATE_FAILED);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 上传用户头像 [POST]
     * 接口请求地址：/user/upload_headimg/
     * @param int $uid 用户Id
     * @param string $data 图片数据(base64编码后的内容)
     * @example 返回结果：{"retcode":0,"retmsg":{url:图片URI地址}}
     */
    public function upload_headimgAction() {
        $uid = $this->request->getPost('uid');
        $imgData = $_POST['data'];
        if ($uid > 0) {
            global $config;
            $seed = mt_rand(0, 9);
            $spIndex = strpos($imgData, ',');
            $substr = substr($imgData, 0, $spIndex);
            $imgType = preg_replace('#data:image\/|\;base64#', '', $substr);
            $imgStr = base64_decode(substr($imgData, $spIndex));
            $fext = '.' . $imgType;
            // 上传文件名
            $fname = hash('md4', time() . uniqid());
            // 临时上传目录
            $fpath = APP_PATH . "public/uploads/$seed/";
            if (!is_dir($fpath)) {
                mkdir($fpath, 0777, true);
            }
            $fFullName = $fpath . $fname . $fext;
            // 写入源文件
            file_put_contents($fFullName, $imgStr);
            if (is_file($fFullName)) {
                $user = User::FindFirst("client_id = $uid");
                $user->client_head = $config->base->domain . "uploads/$seed/" . $fname . $fext;
                $user->save();
                $this->echoMsg(0, $user->client_head);
            } else {
                $this->echoErrcode(ErrorCode::$ERR_USERHEAD_UPLOADFAILED);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 上传用户头像(字节流) [GET]
     * 接口请求地址：/user/upload_headimg_bytes/
     * @param int $uid 用户Id url参数的方式传参
     * @param string $attach 文件数据字段
     * @example 返回结果：{"retcode":0,"retmsg":{url:图片URI地址}}
     */
    public function upload_headimg_bytesAction() {
        $uid = $this->request->get('uid');
        if ($uid > 0) {
            global $config;
            $seed = mt_rand(0, 9);
            $base_path = APP_PATH . "public/uploads/$seed/";
            if (!is_dir($base_path)) {
                mkdir($base_path, 0777, true);
            }
            $extname = substr(strrchr(basename($_FILES ['attach'] ['name']), '.'), 1);
            $newname = hash('md4', time() . uniqid()) . '.' . $extname;
            $target_path = $base_path . $newname;
            if (move_uploaded_file($_FILES ['attach'] ['tmp_name'], $target_path)) {
                $user = User::FindFirst("client_id = $uid");
                $user->client_head = $config->base->domain . "uploads/$seed/" . $newname;
                $user->save();
                $this->echoMsg(0, $user->client_head);
            } else {
                $this->echoErrcode(ErrorCode::$ERR_USERHEAD_UPLOADFAILED);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 拉取用户信息 [POST]
     * 接口请求地址：/user/get_info/
     * @param int $uid 用户Id
     * @example 返回结果：{"retcode":0,"retmsg":{"client_id":"77","client_name":"陈永才","client_sex": 0, client_phone":"18565518404", "client_joindate":"2015-11-08", "client_credit":"0", "client_head":"#图片地址#"}}
     *
     */
    public function get_infoAction() {
        $uid = $this->request->getPost('uid');
        if ($uid > 0) {
            $user = User::FindFirst(array(
                "client_id = $uid",
                'columns' => 'client_id, client_name, client_sex, client_phone, client_joindate, client_credit, client_head'
            ));
            if (false !== $user) {
                $userInfo = $user->toArray();
                if ($userInfo['client_sex'] == 'm') {
                    $userInfo['client_sex'] = 0;
                } else {
                    $userInfo['client_sex'] = 1;
                }
                $this->echoMsg(0, Util::digitFix($userInfo));
            } else {
                // 用户不存在
                $this->echoErrcode(ErrorCode::$ERR_USER_DOESNOTEXT);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 添加或删除收藏 [POST]
     * 接口请求地址：/user/set_like/
     * @param int $uid 用户Id
     * @param int $product_id 商品Id
     * @example 如果product_id为正数，则添加收藏，如果为负数，则为删除对应绝对值product_id的商品收藏
     * @example 返回结果：{"retcode":0,"retmsg":"Success"}}
     */
    public function set_likeAction() {
        $uid = $this->request->getPost('uid');
        $product_ids = $this->request->getPost('product_id');
        $product_ids = explode(',', $product_ids);
        if ($uid > 0) {
            foreach ($product_ids as $product_id) {
                $product_id = trim($product_id);
                if (empty($product_id)) {
                    continue;
                }
                // 循环处理
                if ($product_id > 0) {
                    // 检查存在性
                    $ext = UserLike::findFirst("uid = $uid AND product_id = $product_id");
                    if (!$ext) {
                        // 添加收藏
                        $Like = new UserLike();
                        $Like->uid = $uid;
                        $Like->product_id = $product_id;
                        try {
                            $Like->save();
                        } catch (Exception $ex) {
                            continue;
                        }
                    } else {
                        // 收藏信息不存在
                        continue;
                    }
                } else if ($product_id < 0) {
                    // 删除收藏
                    $product_id = abs($product_id);
                    $Like = UserLike::findFirst("uid = $uid AND product_id = $product_id");
                    if ($Like) {
                        try {
                            $Like->delete();
                        } catch (Exception $ex) {
                            continue;
                        }
                    } else {
                        // 收藏信息不存在
                        continue;
                    }
                }
            }
            $this->echoSuccess();
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 拉取用户收藏列表 [GET]
     * 接口请求地址：/user/get_likes/
     * @param int $uid 用户Id
     * @example 返回结果：{"retcode":0,"retmsg":[{"product_id":26,"product_name":"Apple MacBook 12 英寸笔记本电脑 512GB金色MK4N2CH/A","sell_price":0.1,"product_image":"http://182.92.164.200:83/uploads/product_hpic/144172333255eef3c427f89.jpg","product_unit":"","product_instocks":0,"product_storage":"","product_origin":"","product_breif":""},{"product_id":28,"product_name":"Apple MacBook 12 英寸笔记本电脑 512GB金色MK4N2CH/A","sell_price":0.1,"product_image":"http://182.92.164.200:83/uploads/product_hpic/144172333255eef3c427f89.jpg","product_unit":"","product_instocks":0,"product_storage":"","product_origin":"","product_breif":""},{"product_id":29,"product_name":"Apple MacBook 12 英寸笔记本电脑 512GB金色MK4N2CH/A","sell_price":0.1,"product_image":"http://182.92.164.200:83/uploads/product_hpic/144172333255eef3c427f89.jpg","product_unit":"","product_instocks":0,"product_storage":"","product_origin":"","product_breif":""}]}
     */
    public function get_likesAction() {
        global $config;
        $uid = $this->request->get('uid');
        if ($uid > 0) {
            $products = [];
            $likes = UserLike::find("uid = $uid");
            foreach ($likes as $key => $value) {
                try {
                    $product = Product::findFirst([
                        "product_id = $value->product_id AND is_delete = 0",
                        "columns" => "product_id, product_name, sell_price, catimg AS product_image, product_unit, product_instocks, product_storage, product_origin, product_subname AS product_breif"
                    ]);
                    if (!$product) {
                        // 商品信息不存在，删除收藏信息
                        $likes->delete();
                        continue;
                    }
                    $product->product_image = $config->base->domainbase . 'uploads/product_hpic/' . $product->product_image;
                    $products[] = $product->toArray();
                } catch (Exception $ex) {
                    continue;
                }
            }
            $this->echoMsg(0, Util::digitFix($products));
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 拉取用户收货地址列表 [GET]
     * 接口请求地址：/user/get_addresses/
     * @param int $uid 用户Id
     * @example 返回结果：{"retcode":0,"retmsg":[
     *      {aid:"1", uname: "地址1", phone: "", province: "", city: "", dist: "", addrs: "", poscode: "", isdefault: 1}},
     *      {aid:"2", uname: "地址2", phone: "", province: "", city: "", dist: "", addrs: "", poscode: "", isdefault: 0}}
     * ]}
     * @return null
     */
    public function get_addressesAction() {
        $uid = $this->request->get('uid');
        if ($uid > 0) {
            $address = Address::find([
                "uid = $uid", "order" => "isdefault DESC"
            ]);
            if ($address->count() > 0) {
                $this->echoMsg(0, Util::digitFix($address->toArray()));
            } else {
                $this->echoMsg(0, []);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 编辑收货地址信息 [POST]
     * 接口请求地址：/user/set_address/
     * @param int $aid 地址Id aid为0则新增收货地址，aid>0则编辑
     * @param int $uid 用户Id (必须)
     * @param string $uname 收货人 (必须)
     * @param string $phone 电话 (必须)
     * @param string $province 省名
     * @param string $city 城市名
     * @param string $dist 区名
     * @param string $addrs 详细地址
     * @param string $poscode 邮政编码
     * @param int $isdefault 是否为默认地址，1为是，0为否
     * @example 设置默认地址之后，每次拉取收货地址，默认地址在前
     * @example 返回结果：{"retcode":0,"retmsg":{Success}}
     * @return null
     */
    public function set_addressAction() {
        $aid = $this->request->getPost('aid');
        $uid = $this->request->getPost('uid');
        $uname = trim($this->request->getPost('uname'));
        $phone = trim($this->request->getPost('phone'));
        $province = trim($this->request->getPost('province'));
        $city = trim($this->request->getPost('city'));
        $dist = trim($this->request->getPost('dist'));
        $addrs = trim($this->request->getPost('addrs'));
        $poscode = trim($this->request->getPost('poscode'));
        $isdefault = InputUtil::digitDefault($this->request->getPost('isdefault'), 0);

        if (empty($uid)) {
            return $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        } else {
            // 检查用户存在
            $user = User::findFirst("client_id = $uid");
            if (!$user) {
                return $this->echoErrcode(ErrorCode::$ERR_ADDRESS_USERNOTEXT);
            }
            if ($aid == 0) {
                // 新增地址 检查个数限制
                $addresses = Address::find("uid = $uid");
                if ($addresses->count() >= 5) {
                    return $this->echoErrcode(ErrorCode::$ERR_ADDRESS_TOOMUSH);
                }
            }
        }
        if (empty($uname)) {
            return $this->echoErrcode(ErrorCode::$ERR_ADDRESS_NAME);
        }
        if (empty($province)) {
            return $this->echoErrcode(ErrorCode::$ERR_ADDRESS_PROVINCE);
        }
        if (empty($city)) {
            return $this->echoErrcode(ErrorCode::$ERR_ADDRESS_CITY);
        }
        if (empty($addrs)) {
            return $this->echoErrcode(ErrorCode::$ERR_ADDRESS_ADDR);
        }
        if (!preg_match("/^1[3|4|5|7|8][0-9]\\d{8}$/", $phone)) {
            return $this->echoErrcode(ErrorCode::$ERR_ADDRESS_PHONE);
        }
        if (!preg_match("/^\\d{6}$/", $poscode)) {
            return $this->echoErrcode(ErrorCode::$ERR_ADDRESS_POSCODE);
        }

        if (!empty($uname) && !empty($phone) && $uid > 0) {
            if ($aid == 0) {
                // 新增收货地址
                $address = new Address();
                $address->uid = $uid;
            } else {
                // 编辑
                $address = Address::findFirst("aid = $aid AND uid = $uid");
                if (!$address) {
                    $this->echoErrcode(ErrorCode::$ERR_ADDRESS_DOESNOTEXT);
                    return;
                }
            }
            $address->uname = $uname;
            $address->phone = $phone;
            $address->isdefault = $isdefault;
            !empty($province) && $address->province = $province;
            !empty($city) && $address->city = $city;
            !empty($dist) && $address->dist = $dist;
            !empty($addrs) && $address->addrs = $addrs;
            !empty($poscode) && $address->poscode = $poscode;
            try {
                if ($isdefault > 0) {
                    $addresses = Address::find("uid = $uid");
                    foreach ($addresses as $adr) {
                        $adr->isdefault = 0;
                        $adr->save();
                    }
                }
                $address->save();
                $this->echoSuccess();
            } catch (Exception $ex) {
                $this->echoErrcode(ErrorCode::$ERR_SYSTEM_FAILED);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 删除收货地址 [POST]
     * 接口请求地址：/user/del_address/
     * @param int $aid 地址Id
     * @example 返回结果：{"retcode":0,"retmsg":{Success}}
     */
    public function del_addressAction() {
        $aid = $this->request->getPost('aid');
        if ($aid > 0) {
            $address = Address::findFirst("aid = $aid");
            if ($address) {
                try {
                    $address->delete();
                    $this->echoSuccess();
                } catch (Exception $ex) {
                    $this->echoErrcode(ErrorCode::$ERR_SYSTEM_FAILED);
                }
            } else {
                $this->echoErrcode(ErrorCode::$ERR_ADDRESS_DOESNOTEXT);
            }
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

    /**
     * 获取验证码 [GET]
     * 接口请求地址：/user/get_valicode/
     * @example 返回结果：{"retcode":0,"retmsg":{code: "v4fp", url: "图片URL"}}
     * @example 验证判断忽略大小写
     */
    public function get_valicodeAction() {
        global $config;
        $vc = new ValidateCode();
        $vc->doimg();
        $code = $vc->getCode();
        $fname = $vc->getFile();
        if (!empty($code)) {
            $this->echoMsg(0, ["code" => $code, "url" => $config->base->domain . 'valicode/' . $fname]);
        } else {
            $this->echoErrcode(ErrorCode::$ERR_SYSTEM_FAILED);
        }
    }

    /**
     * 获取用户积分记录 [GET]
     * 接口请求地址：/user/get_credit_records/]
     * @param int uid 用户id
     * @example 样品JSON : <a href="http://182.92.164.200:82/json_user_credit_record.json" target="_blank">http://182.92.164.200:82/json_user_credit_record.json</a>
     */
    public function get_credit_recordsAction() {
        $uid = $this->request->get('uid');
        if ($uid > 0) {
            // 获取用户积分
            $user = User::findFirst([
                "client_id = $uid", "columns" => "client_credit"
            ]);
            $sqlBulider = $this->modelsManager->createBuilder();
            $sqlBulider->where("uid = $uid");
            $list = $sqlBulider->columns('od.order_id,od.serial_number,crd.amount,crd.dt AS datetime')->from(['crd' => 'CreditRecord'])->leftJoin('Order', 'od.order_id = crd.relid', 'od')->getQuery()->execute()->toArray();
            foreach ($list as &$ods) {
                $ods['order_details'] = Order::getOrderDetails($ods['order_id']);
            }
            $this->echoMsg(0, [
                'user_credit' => $user->client_credit, 'credit_records' => $list
            ]);
        } else {
            $this->echoErrcode(ErrorCode::$ERR_PARAMS_ERROR);
        }
    }

}
